<template>
  <div class="login_page">
    <form @submit.prevent="handleSubmit" class="login_box">

      <h2>用户登录</h2>

      <input id="username" type="text"  
          v-model="form.username" 
          placeholder="请输入账号"/>

      <input id="password" type="password"
          v-model="form.password"
          placeholder="请输入密码"/>

      <button class="login" type="submit" :disabled="isSubmitting">
        {{ isSubmitting ? '登录中...' : '立即登录' }}
      </button>

    </form>
    
    <div class="btnList">
      <router-link to="/register"><button>注册</button></router-link>
      <router-link to="/reset"><button>找回密码</button></router-link>
    </div>

  </div>
</template>










<script setup>
import { ref } from 'vue';
import { login } from '../api/BlogAuth';
import { useRouter } from 'vue-router';
import { emitter } from '@/router/eventBus';
import server from '../api/server';

const router = useRouter();

const isSubmitting = ref(false);

const form = ref({
  username: '',
  password: ''
});

const handleSubmit = async () => {

  isSubmitting.value = true;

  try {

    await login(form.value).then((res)=>{
      console.log(form.value)
      if(res.data.code == 0){
        server.token = res.data.data["password"]
        server.currentUserId = res.data.data["id"]
        alert('登录成功: ' + res.data.data["username"]);
        router.push('/');
        emitter.emit("avatar_change", res.data)
      }else{

        alert('登录失败'+res.data.msg);

      }
    })
    
  } catch (error) {

    alert('登录失败'+error);

  } finally {

    isSubmitting.value = false;

  }
};
</script>














<style scoped>
.login_page{
  display: flex;flex-flow: column nowrap;
  align-items: center;
}

.login_box {
  display: flex;flex-flow: column nowrap;
  width: 400px;gap: 1.5rem;
  padding: 2rem; margin: 200px auto 0px;
  
  background-color: #f5f5f5;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.login_box button.login {
  padding: 0.75rem;
  background-color: #646cff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login_box button.login:hover {
  background-color: #535bf2;
}

.login_box button.login:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.btnList{
  display: flex;flex-flow: row nowrap;
  justify-content: space-between;
  margin-top: 10px;
}

.btnList button{
  display: block;
  width: 70px;height: 30px;margin-right: 30px;
  
  text-decoration: none;
  background-color: #ff6699;
  border: none;
  color: white;
  border-radius: 4px;
}

.login_box>h2{
  display: block;text-align: center;
  margin: 0;
}

input {
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

input:focus {
  outline: none;
  border-color: #646cff;
}

</style>